package com.agileai.crm.common;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;

import com.agileai.util.IOUtil;

public class ExcelFileHelper {
	private HttpServletRequest request = null;
	private HttpServletResponse response = null;
	
	public ExcelFileHelper(HttpServletRequest request,HttpServletResponse response){
		this.request = request;
		this.response = response;
	}
    
	public String getTemplateDirPath(){
		String result = null;
		try {
			  URL url = Thread.currentThread().getContextClassLoader().getResource("");
			  File classesFolder = new File(url.toURI());
			  result = classesFolder.getParentFile().getParentFile().getAbsolutePath()
					  +File.separatorChar+"repository"+File.separatorChar+"excels";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
    
	public void downloadFile(InputStream inputStream,String downloadFileName)  {
        try {
        	this.setReponse(downloadFileName);
        	OutputStream outputStream = response.getOutputStream();
        	IOUtil.copy(inputStream, outputStream);
        	IOUtils.closeQuietly(inputStream);
        	IOUtils.closeQuietly(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	
	public void setReponse(String fileName){
    	String agent = request.getHeader("USER-AGENT");
        try {
        	fileName= encodeFileName(fileName,agent);
   	    } catch (UnsupportedEncodingException e) {
   	    	e.printStackTrace();
   		}
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        response.setDateHeader("Expires", (System.currentTimeMillis() + 1000));
	}
	
	private String encodeFileName(String fileName, String agent) throws UnsupportedEncodingException{
		String codedfilename = null;
		fileName=fileName.replaceAll("\n|\r", " ").trim();
		if (null != agent && (-1 != agent.indexOf("MSIE") || -1 != agent.indexOf("Trident"))) {
			codedfilename = URLEncoder.encode(fileName, "UTF8");
		} else if (null != agent && -1 != agent.indexOf("Mozilla")) {
			codedfilename = "=?UTF-8?B?"+(new String(Base64.encodeBase64(fileName.getBytes("UTF-8"))))+"?=";
		} else {
			codedfilename = fileName;
		}
		return codedfilename;
	}	  
}
